package com.technology.education.ui.common.feedback

import androidx.lifecycle.MutableLiveData
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.technology.education.ext.toast
import com.technology.education.network.apiService
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class FeedBackViewModel : BaseViewModel() {
    var content = ""
    var selectedPhotos = mutableListOf<Photo>()
    val result = MutableLiveData<Boolean>()

    fun upload() {
        val builder = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
        selectedPhotos.forEach {
            val imageBody: RequestBody =
                RequestBody.create(MediaType.parse("multipart/form-data"), File(it.path))
            builder.addFormDataPart(
                "file",
                it.name,
                imageBody
            )
        }
        request({
            apiService.uploadFile(builder.build().parts())
        }, success = {
            commitData(it)
        }, isShowDialog = true)
    }

    fun commitData(images: List<String>?) {
        request({
            apiService.feedBack(hashMapOf("content" to content, "images" to images))
        }, success = {
            result.postValue(true)
        }, error = {
            toast(it.errorMsg)
        }, isShowDialog = true)
    }
}